package com.nl.controller.web.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.web.bean.SmsBaseStation;
import com.nl.controller.web.bean.SmsReportTotal;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.mapper.SmsBaseStationMapper;
import com.nl.controller.web.mapper.SmsReportTotalMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsReportTotalService {

    @Autowired
    private SmsReportTotalMapper smsReportTotalMapper;

    @Autowired
    private CommonService commonService;
    
    
    @Autowired
    private SmsBaseStationMapper smsBaseStationMapper;

    @SystemServiceLog(description = "短信发送量统计分析查询", value = false)
    public PageInfo<SmsReportTotal> find
            (SmsUsers smsUsers, int page, int limit, String month, String way, String startTime, String endTime, String countWay, String cityId,String mgrType, String mgrId, String mgrName, String regionId, String stationId, String countyId, String year) {
        List<SmsReportTotal> list = new ArrayList<>();
        PageHelper.startPage(page, limit);
        try {
            list = this.getDataList(smsUsers, way, month, startTime, endTime, countWay,cityId,mgrType,mgrId,mgrName,regionId,stationId,countyId,year);
        } catch (Exception e) {
            throw new SmsException("短信发送量统计分析查询失败");
        }
        PageInfo<SmsReportTotal> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    @SystemServiceLog(description = "短信发送量统计明细导出", value = false)
    public JSONArray download
            (SmsUsers smsUsers, String way, String month, String startTime, String endTime, String countWay,String cityId,String mgrType,String mgrId,String mgrName,String regionId,String stationId,String countyId,String year) {
        {
            List<SmsReportTotal> list = new ArrayList<>();
            try {
                list = this.getDataList(smsUsers, way, month, startTime, endTime, countWay,cityId,mgrType,mgrId,mgrName,regionId,stationId,countyId,year);
                if(!"".equals(mgrId)&&null!=mgrId){
                    commonService.createSmsOperLog("7", mgrId,"导出发送统计报表："+mgrId, "0", "23");
                }else{
                    commonService.createSmsOperLog("7", "0","导出发送统计报表", "0", "23");
                }
            } catch (Exception e) {
                if(!"".equals(mgrId)&&null!=mgrId){
                    commonService.createSmsOperLog("7", mgrId,"导出发送统计报表："+mgrId, "1", "23");
                }else{
                    commonService.createSmsOperLog("7", "0","导出发送统计报表", "1", "23");
                }
                throw new SmsException("短信发送量统计分析导出失败");
            }
            JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(list));
            return jsonArray;
        }
    }

    public List<SmsReportTotal> download2
            (SmsUsers smsUsers, String way, String month, String startTime, String endTime, String countWay,String cityId,String mgrType,String mgrId,String mgrName,String regionId,String stationId,String countyId,String year) {
        {
            List<SmsReportTotal> list = new ArrayList<>();
            try {
                list = this.getDataList(smsUsers, way, month, startTime, endTime, countWay,cityId,mgrType,mgrId,mgrName,regionId,stationId,countyId,year);
                if(!"".equals(mgrId)&&null!=mgrId){
                    commonService.createSmsOperLog("7", mgrId,"导出发送统计报表："+mgrId, "0", "23");
                }else{
                    commonService.createSmsOperLog("7", "0","导出发送统计报表", "0", "23");
                }
            } catch (Exception e) {
                if(!"".equals(mgrId)&&null!=mgrId){
                    commonService.createSmsOperLog("7", mgrId,"导出发送统计报表："+mgrId, "1", "23");
                }else{
                    commonService.createSmsOperLog("7", "0","导出发送统计报表", "1", "23");
                }
                throw new SmsException("短信发送量统计分析导出失败");
            }
            //JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(list));
            return list;
        }
    }
    /**
     * 获取区县名称
     * @param list
     * @return
     */
    private List<SmsReportTotal> SetCountyName(List<SmsReportTotal> list){
    	if (!list.isEmpty()) {
			for (SmsReportTotal smsReportTotal : list) {
				String countyId = smsReportTotal.getCountyId();
				if (null == countyId || "".equals(countyId))  {
					smsReportTotal.setCountyName("—");
//					return list;
					continue;
				}
				String countyName = smsReportTotalMapper.getCountyName(countyId);
				smsReportTotal.setCountyName(countyName);
			}
		}
		return list;
    }
    
    private List<SmsReportTotal> SetCountyName2(List<SmsReportTotal> list){
    	if (!list.isEmpty()) {
			for (SmsReportTotal smsReportTotal : list) {
				smsReportTotal.setCountyName("  —");
			}
		}
		return list;
    }
    
    private List<SmsReportTotal> SetMgrType(List<SmsReportTotal> list){
    	if (!list.isEmpty()) {
			for (SmsReportTotal smsReportTotal : list) {
				String mgrType = smsReportTotal.getMgrType();
				if (null == mgrType || "".equals(mgrType))  {
//					return list;
					continue;
				}
				String typeName = smsReportTotalMapper.findMgrTypeById(mgrType);
				smsReportTotal.setMgrType(typeName);
			}
		}
		return list;
    }
    
    /**
     * 获取项目的短信通道号
     * @param list
     * @return
     */
    private List<SmsReportTotal> SetSender(List<SmsReportTotal> list){
    	if (!list.isEmpty()) {
			for (SmsReportTotal smsReportTotal : list) {
				String mgrId = smsReportTotal.getMgrId();
				String cityId = smsReportTotal.getCityId();
				if (null == mgrId || "".equals(mgrId))  {
//					return list;
					continue;
				}
				String cityExtId = smsReportTotalMapper.getCityExtId(mgrId);
				if("11".equals(cityId)){
					cityExtId = "106571103"+cityExtId;
				}else{
					cityExtId = "106571102"+cityExtId;
				}
				smsReportTotal.setSender(cityExtId);
			}
		}
		return list;
    }
    
    
    @SystemServiceLog(description = "短信发送量统计查询数据获取", value = false)
    private List<SmsReportTotal> getDataList(SmsUsers smsUsers, String way, String month, String startTime, String endTime, String countWay,String cityId,String mgrType,String mgrId,String mgrName,String regionId,String stationId,String countyId,String year) {
        List<SmsReportTotal> list = null;
        String duty = smsUsers.getDuty();
        Map<String, Object> map = new HashMap<>();
        //地市管理员限制
        if ("1".equals(duty)) {
            map.put("cityId", smsUsers.getCityId());
            
        } else if ("2".equals(duty)) {
        	map.put("countyId", smsUsers.getCountyId());
            
        }else if ("3".equals(duty)) {//项目管理员限制
            map.put("mgrIdList", smsUsers.getMgrId().split(","));
            
        }else{
        	map.put("cityId", cityId);
        }
        if ("0".equals(way)) {
            map.put("month", month);
        } else if ("2".equals(way)) {
            map.put("year", year);
        } else {
            map.put("startTime", startTime);
            map.put("endTime", endTime);
        }
        //统计数据是否包含当天数据
        int result=this.judeContainNow(way, month, startTime, endTime);
        try {
            if ("city".equals(countWay)) {
                log.info("根据地市查询短信发送统计");
                if(result==1){
                    list = smsReportTotalMapper.findByCity2(map);
                }else{
                    list = smsReportTotalMapper.findByCity(map);
                }
                list = this.SetCountyName(list);
            } else if (("mgr").equals(countWay)) {
                log.info("根据项目查询发送统计");
                map.put("cityId",cityId);
                map.put("mgrId",mgrId);
                map.put("mgrName",mgrName);
                map.put("countyId",countyId);
                
                if(result==1){
                	list = smsReportTotalMapper.findByMgr2(map);
                }else{
                	list = smsReportTotalMapper.findByMgr(map);

                }

                list=this.SetSender(list);
                list = this.SetCountyName(list);
            } else if (("type").equals(countWay)) {
                log.info("根据项目查询发送统计");
                map.put("cityId",cityId);
                map.put("mgrType",mgrType);
                map.put("countyId",countyId);
                
                if(result==1){
                	list = smsReportTotalMapper.findByType2(map);
                }else{
                	list = smsReportTotalMapper.findByType(map);
                }

                list=this.SetSender(list);
                if((countyId != null && countyId != "")||(cityId !=null && cityId !="")){
                	list = this.SetCountyName(list);
                }else{
                	list = this.SetCountyName2(list);
                }
                list = this.SetMgrType(list);
            }else if (("content").equals(countWay)) {
                log.info("根据短信内容查询发送统计");
                map.put("cityId",cityId);
                map.put("mgrId",mgrId);
                map.put("mgrName",mgrName);
                map.put("countyId",countyId);
                if(result==1){
                    list = smsReportTotalMapper.findByContent2(map);
                }else{
                    list = smsReportTotalMapper.findByContent(map);

                }
                
                list=this.SetSender(list);
                list = this.SetCountyName(list);
            }else if (("region").equals(countWay)) {
            	log.info("根据区域查询发送统计");
                map.put("cityId",cityId);
                map.put("regionId",regionId);
                map.put("mgrId",mgrId);
                map.put("countyId",countyId);
                map.put("mgrName",mgrName);
                
                if(result==1){
                	list = smsReportTotalMapper.findByRegion2(map);
                }else{
                	list = smsReportTotalMapper.findByRegion(map);

                }
                

                list = this.SetCountyName(list);
            } else if(("Station").equals(countWay)){
                map.put("cityId",cityId);
                map.put("mgrId",mgrId);
                map.put("regionId",regionId);
                map.put("stationId",stationId);
                map.put("countyId",countyId);
                map.put("mgrName",mgrName);
                log.info("根据基站查询发送统计");
                
                if(result==1){
                	list = smsReportTotalMapper.findByStation2(map);
                }else{
                	list = smsReportTotalMapper.findByStation(map);

                }
                list=this.SetStationInfo(list);
                
                list = this.SetCountyName(list);
            } else if(("county").equals(countWay)){
                map.put("cityId",cityId);
                map.put("mgrId",mgrId);
                map.put("regionId",regionId);
                map.put("stationId",stationId);
                map.put("countyId",countyId);
                log.info("根据区县查询发送统计");
                
                if(result==1){
                	list = smsReportTotalMapper.findByCounty2(map);
                }else{
                	list = smsReportTotalMapper.findByCounty(map);
                }
                list = this.SetCountyName(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信发送量统计数据获取出现异常：" + countWay);
				throw e;
        }
        return list;
    }
    
    private int judeContainNow(String way,String month,String startTime,String endTime){
    	SimpleDateFormat ft = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat ft2 = new SimpleDateFormat("yyyyMM");
        Date date = new Date();
        String time = ft.format(date);
        String nowMonth = ft2.format(date);
        if(("1".equals(way)&&time.equals(endTime))||("0".equals(way)&&nowMonth.equals(month))||("2".equals(way))){
        	return 1;
        }else{
        	return 0;
        }
    }
    
    private List<SmsReportTotal> SetStationInfo(List<SmsReportTotal> list){
    	HashMap<String, SmsBaseStation> hashMap = new HashMap<String, SmsBaseStation>();
    	HashMap<String, Object> param = new HashMap<String, Object>();
    	List<SmsBaseStation> baseStationList;
    	SmsBaseStation smsBaseStation=new SmsBaseStation();
    	if(list!=null){
    		for(SmsReportTotal smsReportTotal : list){
    			String mgrId =  smsReportTotal.getMgrId();
				String stationId = smsReportTotal.getStationId();
				
				if (stationId!=null && !"".equals(stationId)) {
						param.put("mgrId", mgrId);
						param.put("stationId",stationId);
						baseStationList = smsBaseStationMapper.findSmsBaseStation(param);
						if(baseStationList.size()!=0){
							smsBaseStation=baseStationList.get(0);
						}else{
							smsBaseStation.setStationName("暂无数据");
							smsBaseStation.setRegionId("暂无数据");
							smsBaseStation.setRegionName("暂无数据");
						}; 					
					smsReportTotal.setStationName(smsBaseStation.getStationName());
					smsReportTotal.setRegionId(smsBaseStation.getRegionId());
					smsReportTotal.setRegionName(smsBaseStation.getRegionName()); 
					
				}
    		}
    	}
    	return list;
    }
}




